package com.opdar.platform.gateway.beans;

import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.base.Router;
import com.opdar.platform.core.base.RouterManager;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by shiju on 2018/1/4.
 */
public class RouteValidator {
    static class FieldValidator {
        private String name;
        private String path;
        private String type;
        private Boolean must;
        private String mustErrMsg;
        private Boolean checkLength;
        private Integer lengthText;
        private String lengthErrMsg;
        private Boolean regex;
        private String regexText;
        private String regexErrMsg;
    }

    Map<String, Map<String, FieldValidator>> fieldValidatorMap = new HashMap<String, Map<String, FieldValidator>>();

    public boolean validate(String route, String fieldName, Object value) {
        if (RouterManager.contains(route, 0)) {
            Router router = RouterManager.get(route, 0);
            FieldValidator fieldValidator = fieldValidatorMap.get(route).get(fieldName);
            if (fieldValidator.must && StringUtils.isEmpty(value)) {
                int code = 65530;
                writeErrResponse(code, fieldValidator.mustErrMsg);
                return false;
            }
            if(fieldValidator.checkLength){
                //检查长度
                if(value != null && String.valueOf(value).length() < fieldValidator.lengthText){
                    int code = 65531;
                    writeErrResponse(code, fieldValidator.lengthErrMsg);
                    return false;
                }
            }

            if(fieldValidator.regex){
                //检查长度
                if(StringUtils.isEmpty(value) || String.valueOf(value).length() < fieldValidator.lengthText){
                    int code = 65531;
                    writeErrResponse(code, fieldValidator.lengthErrMsg);
                    return false;
                }
            }
        }
        return false;
    }

    private void writeErrResponse(int code, String msg) {
        try {
            String err = "{\"code\": " + code + ", \"msg\": \"" + msg + "\"}\n";
            Context.getResponse().getOutputStream().write(err.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
